package com.heima.behavior.service.impl;

import com.heima.behavior.doc.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.util.LoginUserInfo;
import com.heima.common.util.UserInfoThreadLocal;
import com.heima.model.behavior.dto.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 阅读数据记录
     * @param dto 阅读行为数据
     * @return 响应结果
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1. 校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.error(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        LoginUserInfo user = UserInfoThreadLocal.get();
        if (user == null && dto.getEquipmentId() == null) {
            return ResponseResult.error(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2. 查询用户阅读行为
        Criteria criteria = new Criteria()
                .orOperator(Criteria.where("userId").is(user.getId()), Criteria.where("equipmentId").is(dto.getEquipmentId()))
                .andOperator(Criteria.where("articleId").is(dto.getArticleId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(Query.query(criteria), ApReadBehavior.class);

        //3.阅读行为为空，添加阅读行为
        if (readBehavior != null) {
            readBehavior.setCount(readBehavior.getCount() + 1);
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setReadDuration(dto.getReadDuration());
            mongoTemplate.save(readBehavior);
            return ResponseResult.success(AppHttpCodeEnum.SUCCESS);
        }

        //4.保存关注数据
        readBehavior = ApReadBehavior.builder()
                .userId(user.getId())
                .equipmentId(dto.getEquipmentId())
                .articleId(dto.getArticleId())
                .percentage(dto.getPercentage())
                .loadDuration(dto.getLoadDuration())
                .updatedTime(new Date())
                .createdTime(new Date())
                .readDuration(dto.getReadDuration())
                .count(1)
                .build();

        //5.保存至MongoDB中
        mongoTemplate.save(readBehavior);
        return ResponseResult.success(AppHttpCodeEnum.SUCCESS);
    }
}